<template>
  <div>
    <a-card title="修改个人信息" style="width: auto; height: 790px; border-radius: 15px">
      <a-button slot="extra" type="primary" ghost @click="$router.back()">返回</a-button>
      <a-form-model v-show="!showResult" ref="ruleForm"
                    :rules="rules"
                    :model="form"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol">
        <a-form-model-item prop="username" label="用户名" :colon="false">
          <a-input v-model="form.username" placeholder="用户名" />
        </a-form-model-item>
        <a-form-model-item prop="email" label="邮箱" :colon="false">
          <a-input v-model="form.email" placeholder="邮箱"/>
        </a-form-model-item>
        <a-form-model-item prop="wxNum" label="微信" :colon="false">
          <a-input v-model="form.wxNum" placeholder="微信"/>
        </a-form-model-item>
        <a-form-model-item prop="qqNum" label="Q Q" :colon="false">
          <a-input v-model="form.qqNum" placeholder="Q Q"/>
        </a-form-model-item>
        <a-form-model-item prop="profile" label="个人描述" :colon="false">
          <a-textarea
              v-model="form.profile"
              placeholder="向别人详细介绍一下自己吧"
              :auto-size="{ minRows: 3, maxRows: 5 }"
          />
        </a-form-model-item>
        <a-form-model-item prop="gender" label="性别" :colon="false">
          <a-radio-group v-model="form.gender">
            <a-radio :value="0">男</a-radio>
            <a-radio :value="1">女</a-radio>
            <a-radio :value="-1">保密</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item prop="avatar" label="我的头像" :colon="false">
          <a-upload
              name="avatar"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              action="http://localhost:8080/api/file/upload"
              :before-upload="beforeUpload"
              @change="handleImgChange"
              :headers="headers"
          >
            <img v-if="this.form.avatar" :src="this.form.avatar" alt="宝贝图片" style="width: 100%"/>
            <div v-else>
              <a-icon :type="uploading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>
        </a-form-model-item>
        <a-form-model-item >
          <a-button type="primary" @click="submitForm('ruleForm')" style="width: 30%; margin-left: 25%">
            修改
          </a-button>
          <a-button @click="resetForm('ruleForm')" style="margin-left: 20px; width: 30%">
            重置
          </a-button>
        </a-form-model-item>
      </a-form-model>
      <a-result
          v-show="showResult"
          status="success"
          title="修改成功"
          sub-title="可在'个人中心'中查看修改的个人信息"
      >
        <template #extra>
          <a-button key="console" type="primary" @click="toMyPage">
            返回个人中心
          </a-button>
        </template>
      </a-result>
    </a-card>
  </div>
</template>

<script>
import userStore from "@/store/modules/user";
import {updateLoginUser} from "@/services/user";
export default {
  name: "EditMyInfoPage",
  data() {
    return {
      // 表单相关参数
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      form: {
        username: '',
        email: '',
        gender: 0,
        wxNum: '',
        qqNum: '',
        profile: '',
        avatar: '',
      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 1, max: 8, message: '用户名长度需要小于8', trigger: 'blur'},
          {pattern: '^((?![`~!@#$%^&*()+=|{}\':;\',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]).)*$',
            message: '用户名不能有特殊字符', trigger: 'blur'}
        ],
        email: [
          {pattern: '^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$', message: '请输入正确的邮箱格式', trigger: 'blur'}
        ],
        wxNum: [
          {max: 10, message: '微信号需要小于10', trigger: 'blur'}
        ],
        qqNum: [
          {max: 10, message: 'QQ号需要小于10', trigger: 'blur'}
        ],
        profile: [
          {max: 500, message: '描述内容需要小于500', trigger: 'blur'}
        ],
      },
      showResult: false, // 显示提交结果
      /// 图片上传参数
      uploading: false, // 上传图片加载
      headers: { // 上传图片请求头
        Authorization: "Bearer " + userStore.state.token,
      },
    }
  },
  mounted() {
    this.initUserInfo() // 初始化表单用户信息数据
  },
  methods: {
    initUserInfo() {
      this.form.username = userStore.state.username
      this.form.avatar = userStore.state.avatar
      this.form.profile = userStore.state.profile
      this.form.email = userStore.state.email
      this.form.qqNum = userStore.state.qqNum
      this.form.wxNum = userStore.state.wxNum
      this.form.gender = userStore.state.gender
    },
    /// 表单操作 ////
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 封装修改参数
          let myInfo = {id: userStore.state.id, ...this.form}
          // 修改信息请求
          updateLoginUser(myInfo).then(res => {
            if (res.code === 20000) {
              // 提交成功，显示结果页面
              this.showResult = true
            } else {
              this.$message.error(res.description)
            }
          }).catch(() => {
            this.$message.error('系统异常')
          })
        } else {
          return false;
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 上传图片执行操作
    handleImgChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true; // 上传图片加载
        return;
      }
      if (info.file.status === 'done') {
        this.form.avatar = info.file.response.data // 设置图片url
        this.loading = false;
      }
      if (info.file.status === 'error') {
        this.loading = false;
        this.$message.error('图片上传失败')
        return;
      }
    },
    // 上传前判断图片是否合规
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('只能上传jpeg和png格式图片');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('图片大小需要小于2MB');
      }
      return isJpgOrPng && isLt2M;
    },
    // 返回首页
    toMyPage() {
      this.$router.push('/my/space')
    }
  }
}
</script>

<style scoped>
.numeric-input .ant-tooltip-inner {
  min-width: 32px;
  min-height: 37px;
}

.numeric-input .numeric-input-title {
  font-size: 14px;
}
</style>
